package com.von.springbootnetty.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author xiaosai
 * @version 1.0
 * @date 2022/3/17 13:54:14
 * @describe
 * @className
 */
@Component
public class NettyServer {
    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    @Value("${netty.server.port}")
    private int serverPort;

    public void start(){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup eventLoopGroupWork = new NioEventLoopGroup(128);

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(eventLoopGroup, eventLoopGroupWork)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .option(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT)
                .childHandler(new ServerInitializer());
        try {
            Channel channel = serverBootstrap.bind("0.0.0.0", serverPort).sync().channel();
            logger.info("Netty initialized with port(s): {}",serverPort);
            logger.info("Starting service [Netty]");
            logger.info("Starting Servlet engine: [Netty/{}]","4.1.48.Final");
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
            eventLoopGroupWork.shutdownGracefully();
        }
    }
}
